
package com.ideaquest.entraq;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;

import com.ideaquest.envtraqr.R;

public class MainActivity extends Activity {
    private final static String LOG_TAG = "MainActivity";
    private Timer timer;
    private boolean sending = false;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_main);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        //Do your operation
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
        final String number = ((TelephonyManager) getSystemService(TELEPHONY_SERVICE))
                .getLine1Number();
        final GPSTracker gps = new GPSTracker(this);
        final ImageButton onoffLocation = (ImageButton) findViewById(R.id.sendLocation);

        TimerTask task = new TimerTask() {
            public void run() {
                if (gps.canGetLocation() && sending) {
                	gps.getLocation();
                    log("Can get location");
                    double longitude = gps.getLongitude();
                    double latitude = gps.getLatitude();
                    log("Longitude = " + longitude);
                    log("Latitude = " + latitude);
                    log("Phone number = " + number);
                    postData(longitude, latitude, number);
                }
            }
        };
        timer = new Timer();
        timer.scheduleAtFixedRate(task, 0, 1000);

        onoffLocation.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                log("Clicked");
                if(sending) {
                    sending = false;
                    onoffLocation.setImageDrawable(getResources().getDrawable(R.drawable.red));
                } else {
                    sending = true;
                    onoffLocation.setImageDrawable(getResources().getDrawable(R.drawable.green));
                }
            }
        });
    }

    public void postData(double longitude, double latitude, String phoneNumber) {
        // Create data variable for sent values to server
        DecimalFormat df = new DecimalFormat("###.###");
        String longitudeStr = "" + df.format(longitude);
        String latitudeStr = "" + df.format(latitude);
        String data = "";
        BufferedReader reader = null;
        String text = "";
        try {
            data = URLEncoder.encode("long", "UTF-8")
                    + "=" + URLEncoder.encode(longitudeStr, "UTF-8");

            data += "&" + URLEncoder.encode("lat", "UTF-8") + "="
                    + URLEncoder.encode(latitudeStr, "UTF-8");

            data += "&" + URLEncoder.encode("number", "UTF-8")
                    + "=" + URLEncoder.encode(phoneNumber, "UTF-8");

            URL url = new URL(
                    "http://health.edflanagan.me/update_phone.php?number=XXXXXX&lat=XXX.XXX&long=XXX.XXX");
            URLConnection conn = url.openConnection();
            conn.setDoOutput(true);
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(data);
            wr.flush();

            reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line = null;

            // Read Server Response
            while ((line = reader.readLine()) != null) {
                // Append server response in string
                sb.append(line + "\n");
            }

            text = sb.toString();
        } catch (Exception ex) {
            log(ex.getMessage());
        } finally {
            try {
                reader.close();
            } catch (Exception ex) {
            }
        }

        // Show response on activity
        log(text);

    }

    public void log(String log) {
        Log.d(LOG_TAG, log);
    }
}
